/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-23 15:18:29
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-23 16:30:09
 * @FilePath: /zhuang/Pthread/Pthread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#ifndef _THREAD_HPP_
#define _THREAD_HPP_
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

namespace ThreadModule
{
    
    static int number = 1;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    template <typename T>
    class Thread
    {
     using func_t = function<void(T)>;
    private:
        static void *Routine(void *args)
        {
            // 调用func 它属于类内成员
            Thread *t = static_cast<Thread *>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func(t->_data);
            return nullptr;
        }

        void EnableDetach() // 设置为private
        {
            _joinable = false;
        }

    public:
        Thread(func_t func,T data) : _func(func),_data(data), _status(TSTATUS::NEW), _joinable(true)
        {
            _name = "Thread-" + to_string(number++);
            _pid = getpid();
        }

        string Name()
        {
            return _name;
        }

        bool Start()
        {
            if (_status != TSTATUS::RUNNING) // 状态不是RUNNING才能开始
            {
                int n = pthread_create(&_tid, nullptr, Routine, this);
                if (n != 0)
                    return false;
                return true;
            }
            return false;
        }

        bool Stop()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        bool Join()
        {
            if (_joinable)
            {
                int n = ::pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
 
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }

        bool EnableJoinable()
        {
            return _joinable;
        }
        ~Thread()
        {
        }

    private:
        string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 是否是分离,默认不是分离
        func_t _func;   // 线程要执行的方法
        TSTATUS _status;
        T _data;  
    };

}

#endif